<script setup>
import { ref, onMounted, watch, nextTick, computed, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { marked } from 'marked';
import { getUserInformation, editUserInformation } from '../api/User.js'
import request from '../utils/request.js'
// 导入API
import {
    addAssistantService,
    selectAllService,
    deleteAssistantService,
    editAssistantService
} from '../api/Robot.js';

import AvatarUploadVue from '../components/Avatar.vue'

import {
    selectVoiceChatContentService,
    deleteVoiceChatContentService
} from '../api/ChatMessage.js';

// 导入图标
import {
    SquareUserRound,
    Bot,
    TriangleAlert,
    Pencil,
    Lock,
    Headset,
    Trash,
    LogOut,
    Image,
    UserRoundPen,
    BookText,


} from 'lucide-vue-next';


// 主界面响应式数据

const numInput = ref('');
const assistants = ref([]);
const chatHistory = ref([]);
const currentAssistant = ref(null);
const chatContainer = ref(null); // 聊天容器引用
const avatarRef = ref(null); // 头像容器ref
const profileMenuRef = ref(null); // 下拉菜单ref

// 机器人列表特殊标记
const activeIndex = ref(null);


const maxChars = ref(120);
const DRtext = ref('');


const DRisFocused = ref(false);

function DRhandleEnter(e) {
    if (!DRisFocused.value) return;
    e.preventDefault();
    DRsend();
}


// 模态框状态管理
const modalState = ref({
    hasTape: true,
    showModalBox: false,
    hasCall: false,
    hasInput: false,
    numberInputDisk: false,
    toDeleteModalBox: false,
    toEditModalBox: false,
    topersonEdit: false
});

// 机器人表单数据
const formData = ref({
    addNewRobot: {
        name: '',
        description: '',
        email: ''
    },
    currentRobot: {
        id: '',
        name: '',
        description: '',
        email: ''
    },
    editRobotCopy: {
        id: '',
        name: '',
        description: '',
        email: ''
    }
});


const avatarUrl = ref('');



const showPassword = ref(false);
const isEditing = ref(true);

const userFormData = ref({
    userName: '',
    gender: '',
    phone: '',
    email: sessionStorage.getItem('user') || '',
});

const userErrors = ref({
    name: false,
    phone: false,
    email: false,
    password: false
});



// 监听聊天历史变化，自动滚动到底部
watch(chatHistory, () => {
    nextTick(() => {
        if (chatContainer.value) {
            chatContainer.value.scrollTop = chatContainer.value.scrollHeight;
        }
    });
}, { deep: true });

// 数字键盘处理
const handleNum = (num) => {
    numInput.value += num;
};

const cleanInput = () => {
    numInput.value = '';
};

// 获取机器人列表
const fetchAssistants = async () => {
    try {
        const result = await selectAllService();
        assistants.value = Array.isArray(result) ? result : result.data || [];
    } catch (error) {
        console.error('拉取机器人列表失败:', error);
        alert('获取机器人列表失败，请检查网络或后端服务');
    }
};

// 加载聊天历史
const showChatHistory = async (assistant, index) => {
    currentAssistant.value = assistant;
    activeIndex.value = index;
    console.log(currentAssistant.value.robotId);
    try {
        const historyData = await selectVoiceChatContentService({ robotId: parseInt(currentAssistant.value.robotId) });
        console.log(historyData);
        const conversations = historyData.data || [];
        chatHistory.value = Array.isArray(conversations) ? conversations : [];
        console.log("长度：" + chatHistory.value.length);
    } catch (error) {
        console.error('加载聊天记录失败:', error);
        chatHistory.value = [{
            robotId: assistant.id,
            context: '你好，我是AI助手，有什么可以帮助你的吗？',
            from: "AI",
            time: new Date().toLocaleTimeString()
        }];
    }
};

// 新增机器人
const addBox = () => {
    modalState.value.showModalBox = true;
    const email = sessionStorage.getItem("user");
    formData.value.addNewRobot = { name: '', description: '', email: email };
};

const confirmAdd = async () => {
    if (!formData.value.addNewRobot.name) {
        formData.value.addNewRobot.name = '默认机器人';
    }
    try {
        console.log("111", formData.value.addNewRobot)
        await addAssistantService(formData.value.addNewRobot);
        await fetchAssistants();
        modalState.value.showModalBox = false;
    } catch (error) {
        console.error('添加失败:', error);
        alert(`添加失败: ${error.message || '未知错误'}`);
    }
};

// 取消操作（通用）
const cancelAction = () => {
    modalState.value.showModalBox = false;
    modalState.value.toDeleteModalBox = false;
    modalState.value.toEditModalBox = false;
    formData.value.addNewRobot = { name: '', description: '', email: '' };
    formData.value.editRobotCopy = { id: '', name: '', description: '', email: '' };
};

// 编辑机器人
const editAssistant = (assistant) => {
    formData.value.editRobotCopy = { ...assistant };
    modalState.value.toEditModalBox = true;
};

const confirmEdit = async () => {
    try {
        await editAssistantService(formData.value.editRobotCopy);
        const index = assistants.value.findIndex(item => item.id === formData.value.editRobotCopy.id);
        if (index !== -1) {
            assistants.value[index] = { ...formData.value.editRobotCopy };
        }
        if (currentAssistant.value?.id === formData.value.editRobotCopy.id) {
            currentAssistant.value = { ...formData.value.editRobotCopy };
        }
        modalState.value.toEditModalBox = false;
    } catch (error) {
        console.error('编辑失败:', error);
        alert(`编辑失败: ${error.message || '未知错误'}`);
    }
};

// 删除机器人
const prepareDelete = (assistant) => {
    formData.value.currentRobot = { ...assistant };
    modalState.value.toDeleteModalBox = true;
};

const confirmDelete = async () => {
    console.log(1111, formData.value.currentRobot);
    try {
        await deleteVoiceChatContentService({
            robotId: parseInt(formData.value.currentRobot.id)
        });


        await deleteAssistantService(formData.value.currentRobot);

        await fetchAssistants();

        if (currentAssistant.value?.id === formData.value.currentRobot.id) {
            chatHistory.value = [];
            currentAssistant.value = null;
            activeIndex.value = null;
        }
        modalState.value.toDeleteModalBox = false;
    } catch (error) {
        console.error('删除失败:', error);
        alert(`删除失败: ${error.message || '未知错误'}`);
    }
};



const showInputPad = () => {
    if (modalState.value.hasCall) {
        modalState.value.hasInput = true;
        modalState.value.numberInputDisk = true;
    }
};

const hideInputPad = () => {
    modalState.value.hasInput = false;
    modalState.value.numberInputDisk = false;
    numInput.value = '';
};

// 重置对话
const resetConversation = async () => {
    console.log(currentAssistant.value.robotId)
    if (currentAssistant.value) {
        try {
            await deleteVoiceChatContentService({
                robotId: parseInt(currentAssistant.value.robotId)
            })
        } catch (error) {
            console.error('删除后端聊天记录失败:', error);
        }
    }
    chatHistory.value = [];


};

// 路由控制
const router = useRouter();
const toHumanDesign = (assistant) => {
    router.push({
        name: 'library',
        params: { robotId: assistant.robotId }
    });
};

const handleChangePassword = () => {
    router.push('/resetUserPassword');
}

// 个人信息相关方法
const toPersonEditModal = () => {
    modalState.value.topersonEdit = true;
};



// 取消编辑
const cancelEdit = () => {
    // 重置表单数据
    fetchUserData();
    // 清除错误状态
    clearUserErrors();
    // 退出编辑模式
    isEditing.value = false;
    showPassword.value = false;
    // 关闭模态框（如果不是编辑状态）
    if (!isEditing.value) {
        modalState.value.topersonEdit = false;
    }
};

const handleExit = () => {
    sessionStorage.removeItem('user');
    sessionStorage.removeItem('token');
    router.push('/login')
}

// 获取用户信息
const fetchUserData = async () => {
    try {
        if (!userFormData.value.email) {
            throw new Error('未找到用户邮箱');
        }
        const email = sessionStorage.getItem('user');
        const result = await getUserInformation({ email: email });
        avatarUrl.value = result.data.avatarUrl;

        // 检查 result 和 result.data 是否存在
        if (!result || !result.data) {
            throw new Error('用户数据格式不正确');
        }
        // 更新表单数据
        userFormData.value.userName = result.data.userName || '';
        userFormData.value.gender = result.data.gender || '';
        userFormData.value.phone = result.data.phone || '';

    } catch (error) {
        console.error('错误:', error);
        alert('获取用户信息失败');
    }
};

// 提交个人信息
const handleSubmit = async () => {
    if (!validateUserForm()) return;
    try {
        const formDataToSend = new FormData();
        console.log('表单数据:');
        for (let [key, value] of formDataToSend.entries()) {
            console.log(key, value);
        }

        // 添加表单数据
        Object.keys(userFormData.value).forEach(key => {
            formDataToSend.append(key, userFormData.value[key]);
        });

        console.log('表单数据:', userFormData.value);
        // for (let [key, value] of formDataToSend.entries()) {
        //   console.log(key, value);
        // }
        const response = await editUserInformation(userFormData.value);


        console.log('提交成功:', response.data);

        // 退出编辑模式并关闭模态框
        isEditing.value = false;
        showPassword.value = false;
        modalState.value.topersonEdit = false;

        // 重新获取数据确保同步
        fetchUserData();
    } catch (error) {
        console.error('错误:', error);
        alert('保存个人信息失败，请重试');
    }
};


// 表单验证
const validateUserForm = () => {
    let isValid = true;
    clearUserErrors();

    // 验证昵称
    if (!userFormData.value.userName.trim()) {
        userErrors.value.userName = true;
        isValid = false;
    }

    // 验证手机号
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(userFormData.value.phone)) {
        userErrors.value.phone = true;
        isValid = false;
    }

    return isValid;
};

// 清除错误
const clearUserErrors = () => {
    Object.keys(userErrors.value).forEach(key => {
        userErrors.value[key] = false;
    });
};

const renderMarkdown = (content) => {
    return marked(content);//将Markdown 转换为 HTML
};

// 解析消息内容，分离<think>标签
const parseMessageContent = (content) => {
    const parts = [];
    let remaining = content;

    while (remaining.includes("<think>") && remaining.includes("</think>")) {
        const thinkstart = remaining.indexOf("<think>");
        const thinkEnd = remaining.indexOf("</think>") + "</think>".length;

        // 添加普通内容(<think>之前的部分)
        if (thinkstart > 0) {
            parts.push({ text: remaining.slice(0, thinkstart), isThink: false });
        }

        //提取<think>内容
        const thinkcontent = remaining.slice(thinkstart + "<think>".length, thinkEnd - "</think>".length);
        parts.push({ text: thinkcontent, isThink: true });

        // 剩余部分
        remaining = remaining.slice(thinkEnd);
    }
    // 添加剩余的普通内容
    if (remaining) {
        parts.push({ text: remaining, isThink: false });
    }
    return parts;
};
const isStreaming = ref(false);   // 是否正在流式输出
let currentEventSource = null;

const DRsend = () => {
    if (!DRtext.value.trim()) return;

    // 1. 打断旧流
    if (currentEventSource) {
        currentEventSource.close();
        currentEventSource = null;
    }

    // 2. 用户消息入库
    const userMsg = { from: "User", content: DRtext.value };
    chatHistory.value.push(userMsg);
    const userText = DRtext.value;
    DRtext.value = "";

    // 3. 空 AI 消息占位
    const botMsg = { from: "AI", content: "" };
    chatHistory.value.push(botMsg);

    // 4. 新建 SSE
    const params = new URLSearchParams();
    params.append('promptContent', userText);
    params.append('robotId', parseInt(currentAssistant.value.robotId));

    isStreaming.value = true;                // ✅ 标记开始
    currentEventSource = new EventSource(`/api/chatStream?${params.toString()}`);

    currentEventSource.onmessage = (e) => {
        botMsg.content += e.data;
        chatHistory.value = [...chatHistory.value];
    };

    currentEventSource.onerror = () => {
        currentEventSource.close();
        currentEventSource = null;
        isStreaming.value = false;             // ✅ 标记结束
    };

    currentEventSource.addEventListener('close', () => {
        isStreaming.value = false;
    });
};
const stopStream = () => {
    if (currentEventSource) {
        currentEventSource.close();
        currentEventSource = null;
        isStreaming.value = false;
    }
};
const showProfileActions = ref('')

const handleDocumentClick = (e) => {
    if (!showProfileActions.value) return;
    // 判断点击是否在头像或菜单内
    const isClickInAvatar = avatarRef.value?.contains(e.target);
    const isClickInMenu = profileMenuRef.value?.contains(e.target);
    // 点击外部：关闭菜单
    if (!isClickInAvatar && !isClickInMenu) {
        showProfileActions.value = false;
    }
};

const avatarModal = ref(false);
const toAvatarModal = () => {
    avatarModal.value = !avatarModal.value;
}
// 初始化获取用户头像
const initAvatar = async () => {
    try {
        const email = sessionStorage.getItem('user');
        const res = await request.get('/user/getAvatar', {
            params: {
                email: email  // 这样会被转换为查询参数：/user/getAvatar?email=xxx
            }
        });
        if (res.data.avatarUrl) {
            avatarUrl.value = res.data.avatarUrl;
        }
    } catch (err) {
        console.error('获取头像失败:', err);
    }
};

// 组件挂载时初始化
onMounted(() => {
    fetchAssistants();
    fetchUserData();
    initAvatar();
    document.addEventListener('click', handleDocumentClick); // 绑定事件
});

onUnmounted(() => {
    document.removeEventListener('click', handleDocumentClick); // 移除事件
});


</script>


<template>
    <div class="w-full h-screen flex flex-wrap justify-center">
        <div class="w-[100%] h-[100%] ">
            <!-- 顶部标题区域 -->
            <div class="w-full h-[10%]  flex flex-row min-h-20 items-center relative border-b-1 border-slate-200">
                <div class="w-[100%] h-[100%] z-40">
                    <div class="flex justify-between items-center w-full">
                        <div class="mt-2 ">
                            <div
                                class="mt-[1%] ml-6 font-bold cursor-default text-xl  pl-2 pr-2  rounded w-40 brightness-110">
                                智能语音机器人</div>
                            <div
                                class="mb-2 ml-8 mt-1 font-normal text-sm text-slate-500 brightness-150 cursor-default flex flex-nowrap">
                                提供一站式的智能语音解决方案，基于大模型全面升级NLP能力，显著降低运营成本与门槛。
                            </div>
                        </div>

                        <!-- 头像预览 -->
                        <div class="flex justify-center mr-[5%] mt-2 avatar-preview " ref="avatarRef">
                            <div
                                class="relative w-16 h-16 rounded-full overflow-hidden cursor-pointer shadow-sm preview-avatar hover:scale-120 transition-all">
                                <img v-if="avatarUrl" :src="avatarUrl" alt="用户头像"
                                    class="w-full h-full object-cover transition-transform ">
                            </div>

                            <Transition name="modal">
                                <div ref="profileMenuRef"
                                    class="absolute ml-[10%] top-16 mt-5 w-40 bg-white rounded-lg shadow-lg border border-stone-200 z-50">
                                    <div class="py-2">
                                        <button @click="toAvatarModal"
                                            class="w-full text-left px-4 py-2 text-sm text-slate-700 hover:bg-slate-100 transition-colors flex items-center">
                                            <Image class="mr-2 h-4 w-4 text-green-500" />
                                            修改头像
                                        </button>
                                        <button @click="toPersonEditModal"
                                            class="w-full text-left px-4 py-2 text-sm text-slate-700 hover:bg-slate-100 transition-colors flex items-center">
                                            <UserRoundPen class="mr-2 h-4 w-4 text-blue-500" />
                                            修改信息
                                        </button>
                                        <button @click="handleChangePassword"
                                            class="w-full text-left px-4 py-2 text-sm text-slate-700 hover:bg-slate-100 transition-colors flex items-center">
                                            <Lock class="mr-2 h-4 w-4 text-purple-500" />
                                            修改密码
                                        </button>
                                        <div
                                            class="group w-full text-left px-4 py-2 text-sm text-slate-700 hover:bg-slate-100 transition-colors flex items-center">
                                            <!-- 联系我们文本 -->
                                            <Headset class="text-yellow-500 mr-2 h-4 w-4" />
                                            联系我们
                                            <!-- hover时显示的静态照片（默认隐藏） -->
                                            <div
                                                class="absolute top-[-20%] left-[-20%] transform -translate-x-1/2 mt-2 w-64 h-64 rounded-lg overflow-hidden shadow-lg border-2 border-slate-200 opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-300 z-10">
                                                <img src="../assets/contact.jpg" alt="联系我们"
                                                    class="w-full h-full object-cover">
                                            </div>
                                        </div>
                                        <button @click="handleExit"
                                            class="w-full text-left px-4 py-2 text-sm text-slate-700 hover:bg-slate-100 transition-colors flex items-center">
                                            <LogOut class="mr-2 h-4 w-4 text-red-500" />
                                            退出登录
                                        </button>
                                    </div>
                                </div>
                            </Transition>
                        </div>



                    </div>
                </div>
            </div>

            <!-- 下宽 -->
            <div class="w-full h-[90%] flex  flex-1 ">
                <!-- 下 左窄：机器人列表 -->
                <div class="w-[25%] h-full  flex  items-center justify-center border-r-1 border-slate-200 flex-col">
                    <!-- 新增助手按钮 -->
                    <div @click="addBox"
                        class="w-[80%] mt-[2%] h-[10%] flex items-center justify-center hover:scale-102 transition-all ease-out bg-blue-500 rounded ">
                        <span class="text-white font-black ">+新增助手</span>
                    </div>

                    <!-- 机器人列表 -->
                    <div class="p-4 w-full h-[90%] overflow-auto flex items-center flex-col relative">
                        <!-- 机器人列表项 -->
                        <div class="w-[85%] h-[99%]  rounded-2xl pt-5  overflow-auto flex items-center flex-col">
                            <div v-for="(assistant, index) in assistants" :key="assistant.id" class="w-[80%] h-20 bg-slate-100 mb-4 min-w-[80%] min-h-20 relative rounded shadow-md flex flex-col hover:bg-slate-200 hover:scale-105 focus:outline-none focus:ring-2 focus:ring-blue-400 
          transition-all duration-300 ease-out"
                                :class="{ 'w-[80%] h-20 bg-gradient-to-r from-blue-300 via-slate-100 to-slate-100 border-2 border-blue-400 mb-4 min-w-[80%] min-h-20 relative rounded shadow-md flex flex-col hover:bg-blue-300 focus:outline-none focus:ring-2 focus:ring-blue-400 transition-all duration-300 ease-out animate-custom-bounce': activeIndex === index }"
                                @click="showChatHistory(assistant, index)">
                                <div class="w-[85%] h-full border-r-2 border-slate-500 border-dotted">
                                    <p class="text-black text-base mt-3 ml-3 flex flex-nowrap">{{ assistant.name }}<Bot
                                            class="ml-1 text-blue-500"></Bot>
                                    </p>
                                    <p
                                        class="mt-4 ml-3 text-stone-500 text-xs border-b-2 border-dotted border-slate-500 w-[80%] h-[25%] truncate">
                                        {{ assistant.description }}</p>
                                </div>
                                <div class="w-[15%] h-full absolute right-0 bg-slate-200">
                                    <BookText @click="toHumanDesign(assistant)"
                                        class="absolute cursor-pointer right-0 top-2 rounded w-9 h-4 font-semibold text-lime-500" />
                                    <Pencil @click.stop="editAssistant(assistant)"
                                        class="absolute cursor-pointer  top-8 rounded  right-0 w-9 h-4 font-semibold text-fuchsia-500" />
                                    <Trash @click.stop="prepareDelete(assistant)"
                                        class="absolute cursor-pointer top-14 text-xs  right-0.5 w-8 h-4"
                                        color="#FF6666" />
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 右侧：聊天区域 -->
                <div class="w-[75%] h-full flex items-center justify-center ">
                    <div class="w-full h-[97%] relative flex items-center justify-center mt-2">
                        <div class=" h-[100%] relative w-[100%] rounded-md">
                            <!-- 上顶 -->
                            <div class="w-full h-[8%]  flex items-center flex-nowrap border-b-1 border-slate-200">
                                <div class="ml-5 cursor-default font-medium flex ">
                                    <div class=" pl-2 pr-2 rounded-sm"> {{ currentAssistant?.name ||
                                        'AI会话' }}</div>
                                </div>
                                <button type="button" @click="resetConversation"
                                    class="z-10 absolute right-8 text-stone-700 hover:text-stone-900 text-sm"
                                    :disabled="!currentAssistant"
                                    :class="{ 'z-10 opacity-50 cursor-not-allowed': !currentAssistant }">
                                    ↺重置对话
                                </button>
                            </div>

                            <!-- 聊天内容区域 -->
                            <div class="h-[79%] w-full relative ">
                                <div class=" h-[100%] w-[100%] relative z-10">
                                    <div ref="chatContainer"
                                        class=" w-full h-[100%] overflow-y-auto flex items-center flex-col  scroll-smooth">
                                        <!-- 空状态提示 -->
                                        <div v-if="chatHistory.length === 0 && !currentAssistant"
                                            class="flex flex-col items-center justify-center w-full h-full  bg-slate-100">
                                            <div class="text-7xl">🤖</div>

                                        </div>

                                        <!-- 聊天消息 -->
                                        <div v-if="currentAssistant" class="mt-8 w-full h-full ">
                                            <div v-for="(message, index) in chatHistory" :key="index"
                                                class="w-full message-item mb-4">
                                                <!-- 机器人消息 -->
                                                <div v-if="message.from === 'AI'" class="flex items-start">
                                                    <div
                                                        class="w-12 h-12 rounded-full bg-gradient-to-tl from-teal-500 to-blue-500 flex items-center justify-center ml-5 text-white cursor-default font-bold shadow-sm">
                                                        AI
                                                    </div>
                                                    <div class="ml-3 max-w-[60%]">
                                                        <div
                                                            class=" bg-white rounded-lg p-3 shadow-sm break-words text-stone-800 text-sm">
                                                            <!-- 遍历解析后的数组，key 改为：message.id + part索引 -->
                                                            <div v-for="(part, idx) in parseMessageContent(message.content)"
                                                                :key="`${message.id}-${idx}`" class="mb-1 last:mb-0">
                                                                <!-- 思考内容：加灰色斜体样式 -->
                                                                <div v-if="part.isThink"
                                                                    class="bg-gray-50 px-2 py-1 rounded text-gray-500 text-sm italic">
                                                                    （思考：{{ renderMarkdown(part.text) }}）
                                                                </div>
                                                                <!-- 普通内容：Markdown转HTML -->
                                                                <div v-else v-html="renderMarkdown(part.text)"></div>
                                                            </div>

                                                        </div>
                                                        <div class="text-stone-400 text-xs mt-1 ml-1">
                                                            {{ message.time || '刚刚' }}
                                                        </div>
                                                    </div>
                                                </div>


                                                <!-- 用户消息 -->
                                                <div v-else-if="message.from === 'User'"
                                                    class="flex items-start justify-end">
                                                    <div class="mr-3 max-w-[80%]">
                                                        <div
                                                            class="bg-blue-500 text-slate-100 text-sm rounded-lg p-3 shadow-sm">
                                                            <div>{{ message.content }}</div>
                                                        </div>
                                                        <div class="text-stone-400 text-xs mt-1 ml-1">
                                                            {{ message.time || '刚刚' }}
                                                        </div>
                                                    </div>
                                                    <div
                                                        class="w-12 h-12 rounded-full mr-[2%] bg-gradient-to-tr from-blue-500 to-indigo-600 flex items-center justify-center text-white font-bold shadow-sm">
                                                        <SquareUserRound />
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- 底部输入 -->
                            <div v-if="currentAssistant" class="pl-4 pr-4 pb-1 h-[10%] mt-[2%]">
                                <div class="input-container border-2 border-blue-700 rounded relative h-[90%]">
                                    <textarea v-model="DRtext" @focus="DRisFocused = true" @blur="DRisFocused = false"
                                        @keydown.enter="DRhandleEnter" placeholder="请输入您想问的问题..." :maxlength="maxChars"
                                        class="w-full h-full bg-white/70 p-3 pr-24 text-sm transition-all outline-none resize-none placeholder-gray-400"></textarea>

                                    <div class="absolute bottom-1 right-4 flex items-center gap-2">
                                        <span class="text-xs text-gray-500">{{ DRtext.length }}/{{ maxChars }}</span>

                                        <!-- 发送 / 停止 双态按钮 -->
                                        <button v-if="!isStreaming" @click="DRsend"
                                            class="w-9 h-9 bg-blue-700 rounded text-white text-sm flex items-center justify-center transition-colors">
                                            Send
                                        </button>
                                        <button v-else @click="stopStream"
                                            class="w-9 h-9 bg-red-600 rounded text-white text-sm flex items-center justify-center transition-colors">
                                            Stop
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 新增助手模态框 -->
        <Transition name="modal">
            <div v-if="modalState.showModalBox"
                class="fixed z-50 inset-0 bg-gray-400/70 flex items-center justify-center p-4">
                <div class="w-full max-w-md bg-slate-300 border-2 border-blue-500 rounded-lg shadow-xl overflow-hidden">
                    <div class="p-5 border-b border-gray-200">
                        <div class="text-xl font-semibold">新增助手</div>
                    </div>
                    <form class="p-5" @submit.prevent="confirmAdd" method="post">
                        <div class="mb-4">
                            <label class="block text-xs text-gray-600 mb-1">名称</label>
                            <input type="text" name="name" placeholder="默认机器人" v-model="formData.addNewRobot.name"
                                class="placeholder:text-sm placeholder:text-slate-500 w-full  rounded  bg-slate-200 p-2 focus:outline-none ">
                        </div>
                        <div class="mb-6">
                            <label class="block text-xs text-gray-600 mb-1">描述</label>
                            <textarea v-model="formData.addNewRobot.description" name="description" cols="30" rows="3"
                                class="w-full  rounded  p-2 focus:outline-none bg-slate-200  "></textarea>
                        </div>
                        <div class="flex justify-end gap-3">
                            <button type="button"
                                class="px-4 py-2 border bg-white border-gray-300 rounded-full hover:bg-gray-300 transition-colors"
                                @click="cancelAction">
                                取消
                            </button>
                            <button
                                class="px-4 py-2 bg-blue-600 text-white rounded-full hover:bg-blue-700 transition-colors"
                                type="submit">
                                确定
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </Transition>

        <!-- 删除确认模态框 -->
        <Transition name="modal">
            <div v-if="modalState.toDeleteModalBox"
                class="fixed z-50 inset-0 bg-gray-400/70 flex items-center justify-center p-4">
                <div class="w-full max-w-md bg-slate-300 border-2 border-blue-500 rounded-lg shadow-xl overflow-hidden">
                    <div class="p-5 border-b border-gray-200">
                        <div class="text-xl font-semibold flex items-center">
                            <TriangleAlert class="inline-block mr-2" :stroke-width="3" color="#FF9933" />
                            <span>确定删除对话？</span>
                        </div>
                    </div>
                    <div class="p-5">
                        <p class="text-sm text-gray-500 mb-5">删除后，聊天记录将不可恢复。</p>
                        <div class="flex justify-end gap-3">
                            <button type="button"
                                class="px-4 py-2 border border-gray-300 bg-white  rounded-full hover:bg-gray-100 transition-colors"
                                @click.stop="cancelAction">
                                取消
                            </button>
                            <button
                                class="px-4 py-2 bg-red-600 text-white rounded-full hover:bg-red-700 transition-colors"
                                @click="confirmDelete">
                                删除
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </Transition>

        <!-- 编辑助手模态框 -->
        <Transition name="modal">
            <div v-if="modalState.toEditModalBox"
                class="fixed z-50 inset-0 bg-gray-400/70 flex items-center justify-center p-4">
                <div class="w-full max-w-md bg-slate-300 border-2 border-blue-500 rounded-lg shadow-xl overflow-hidden">
                    <div class="p-5 border-b border-gray-200">
                        <div class="text-xl font-semibold">编辑助手</div>
                    </div>
                    <form class="p-5" @submit.prevent="confirmEdit" method="post">
                        <div class="mb-4">
                            <label class="block text-xs text-gray-600 mb-1">名称</label>
                            <input type="text" name="name" placeholder="默认机器人" v-model="formData.editRobotCopy.name"
                                class="placeholder:text-sm placeholder:text-slate-500 bg-slate-200 w-full border rounded border-gray-300 p-2 focus:outline-none focus:ring-2 focus:ring-blue-500">
                        </div>
                        <div class="mb-6">
                            <label class="block text-xs text-gray-600 mb-1">描述</label>
                            <textarea v-model="formData.editRobotCopy.description" name="description" cols="30" rows="3"
                                class="w-full border rounded border-gray-300 p-2 bg-slate-200 focus:outline-none focus:ring-2 focus:ring-blue-500"></textarea>
                        </div>
                        <div class="flex justify-end gap-3">
                            <button type="button"
                                class="px-4 py-2 border bg-white border-gray-300 rounded-full hover:bg-gray-100 transition-colors"
                                @click="cancelAction">
                                取消
                            </button>
                            <button
                                class="px-4 py-2 bg-blue-600 text-white rounded-full hover:bg-blue-700 transition-colors"
                                type="submit">
                                确定
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </Transition>

        <!-- 个人信息模态框 -->
        <Transition name="modal">
            <div v-if="modalState.topersonEdit"
                class="fixed z-50 inset-0 bg-gray-400/70 flex items-center justify-center p-4">
                <div class="out bg-slate-300 border-2 border-blue-500 p-6 rounded-lg w-[350px] shadow-md">
                    <h2 class="text-center text-gray-800 font-bold mb-5">个人信息</h2>
                    <form class="user-form" @submit.prevent="handleSubmit">
                        <!-- 昵称 -->
                        <div class="info mb-5 relative" :class="isEditing ? 'edit-mode' : ''">
                            <label for="name" class="block mb-2 font-bold text-gray-600">昵称:</label>
                            <input type="text" id="name" v-model="userFormData.userName" placeholder="昵称"
                                :readonly="!isEditing"
                                class="w-full px-3 py-2 border border-gray-300 bg-slate-200 rounded transition-all focus:border-blue-500 focus:outline-none"
                                :class="{ 'bg-gray-100 cursor-not-allowed': !isEditing, 'border-blue-500': isEditing }">
                            <div class="error text-red-500 text-xs mt-1" id="nameError" v-if="userErrors.name">
                                昵称不能为空
                            </div>
                        </div>


                        <!-- 性别 -->
                        <div class="info mb-5" :class="isEditing ? 'edit-mode' : ''">
                            <label for="gender" class="block mb-2 font-bold text-gray-600">性别:</label>
                            <select id="gender" v-model="userFormData.gender" :readonly="!isEditing"
                                class="w-full px-3 py-2 border border-gray-300 bg-slate-200 rounded transition-all focus:border-blue-500 focus:outline-none"
                                :class="{ 'bg-gray-100 cursor-not-allowed': !isEditing, 'border-blue-500': isEditing }">
                                <option value="" disabled selected>请选择性别</option>
                                <option value="男">男</option>
                                <option value="女">女</option>
                            </select>
                        </div>

                        <!-- 手机号 -->
                        <div class="info mb-5 relative" :class="isEditing ? 'edit-mode' : ''">
                            <label for="phone" class="block mb-2 font-bold text-gray-600">手机号码:</label>
                            <input type="tel" id="phone" v-model="userFormData.phone" placeholder="请输入11位手机号码"
                                :readonly="!isEditing"
                                class="w-full px-3 py-2 border bg-slate-200 border-gray-300 rounded transition-all focus:border-blue-500 focus:outline-none"
                                :class="{ 'bg-gray-100 cursor-not-allowed': !isEditing, 'border-blue-500': isEditing }">
                            <div class="error text-red-500 text-xs mt-1" id="phoneError" v-if="userErrors.phone">
                                手机号码需为11位
                            </div>
                        </div>

                        <!-- 邮箱 -->
                        <div class="info mb-5 relative">
                            <label for="email" class="block mb-2 font-bold text-gray-600">邮箱:</label>
                            <input type="email" id="email" v-model="userFormData.email" placeholder="邮箱" readonly
                                class="w-full px-3 py-2 border bg-slate-200 border-gray-300 rounded transition-all focus:border-blue-500 focus:outline-none">
                        </div>

                        <!-- 操作按钮 -->
                        <div class="button-group flex gap-3">
                            <button type="submit" id="saveButton" v-show="isEditing"
                                class="flex-1 py-3 bg-green-600 text-white font-bold rounded hover:bg-green-700 transition-colors">
                                保存
                            </button>
                            <button type="button" id="cancelButton" @click="cancelEdit" v-show="isEditing || !isEditing"
                                class="flex-1 py-3 bg-red-600 text-white font-bold rounded hover:bg-red-700 transition-colors">
                                {{ isEditing ? '取消' : '关闭' }}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </Transition>

        <Transition name="modal">
            <AvatarUploadVue v-if="avatarModal" v-model:avatarModal="avatarModal" v-model:avatarUrl="avatarUrl">
            </AvatarUploadVue>
        </Transition>
    </div>

</template>



<style scoped>
/* 模态框动画 */
.modal-enter-from,
.modal-leave-to {
    opacity: 0;
}

.modal-enter-from .bg-gray-400\/70,
.modal-leave-to .bg-gray-400\/70 {
    opacity: 0;
}

.modal-enter-from>div,
.modal-leave-to>div {
    transform: scale(0.95);
    opacity: 0;
}

.modal-enter-active,
.modal-leave-active {
    transition: all 0.2s ease-out;
}

/* 模态框容器样式 */
.modal-container {
    width: 100%;
    max-width: 500px;
    box-sizing: border-box;
}

@media (max-width: 768px) {
    .modal-container {
        max-width: 90%;
    }
}


/* 自定义跳动动画 */
@keyframes custom-bounce {

    0%,
    100% {
        transform: translateY(0);
    }

    50% {
        transform: translateY(-10px);
    }
}

.animate-custom-bounce {
    animation: custom-bounce 1s infinite;
}

.hidden {
    display: none;
}


/* 蒙板小框动画 */
.rotate-animation {
    animation: rotate 5s linear infinite;
}

@keyframes rotate {
    from {
        transform: rotate(0deg);
    }

    to {
        transform: rotate(360deg);
    }
}



@keyframes bounce {

    0%,
    100% {
        transform: translateY(0);
    }

    50% {
        transform: translateY(-3px);
    }
}


/* 照片容器默认状态：隐藏且透明 */
.group>div:nth-child(2) {
    opacity: 0;
    visibility: hidden;
    transition: opacity 0.3s ease, visibility 0.3s ease, transform 0.3s ease;
    transform: translate(-50%, 10px);
    /* hover前轻微下移，增强动画感 */
}

/* hover状态：显示照片并复位位置 */
.group:hover>div:nth-child(2) {
    opacity: 1;
    visibility: visible;
    transform: translate(-50%, 0);
}

/* 照片适配 */
.group img {
    object-fit: cover;
    /* 避免照片拉伸变形 */
}


/* 照片容器默认状态：隐藏且透明 */
.avatar-preview>div:nth-child(2) {
    opacity: 0;
    visibility: hidden;
    transition: opacity 0.3s ease, visibility 0.3s ease, transform 0.3s ease;
    transform: translate(-50%, 10px);
    /* hover前轻微下移，增强动画感 */
}

/* hover状态：显示照片并复位位置 */
.avatar-preview:hover>div:nth-child(2) {
    opacity: 1;
    visibility: visible;
    transform: translate(-50%, 0);
}
</style>
